Namespace Controls

    <DataGridViewColumnDesignTimeVisible(True)> _
    Public Class DataGridViewColourPickerColumn
        Inherits DataGridViewColumn

        Sub New()
            MyBase.New(New DataGridViewColourPickerCell)
        End Sub

        Public Overrides Property CellTemplate() As System.Windows.Forms.DataGridViewCell
            Get
                Return MyBase.CellTemplate
            End Get
            Set(ByVal value As System.Windows.Forms.DataGridViewCell)
                If Not value.GetType.IsAssignableFrom(GetType(DataGridViewColourPickerCell)) Then
                    Throw New ArgumentException("value not derived from DataGridViewColourPickerCell.")
                Else
                    MyBase.CellTemplate = value
                End If
            End Set
        End Property
    End Class

    Public Class DataGridViewColourPickerCell
        Inherits DataGridViewButtonCell

        Public Shadows ReadOnly Property ValueType() As System.Type
            Get
                Return GetType(Color)
            End Get
        End Property

        Protected Overrides Sub Paint(ByVal graphics As System.Drawing.Graphics, ByVal clipBounds As System.Drawing.Rectangle, ByVal cellBounds As System.Drawing.Rectangle, ByVal rowIndex As Integer, ByVal cellState As System.Windows.Forms.DataGridViewElementStates, ByVal value As Object, ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As System.Windows.Forms.DataGridViewCellStyle, ByVal advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, ByVal paintParts As System.Windows.Forms.DataGridViewPaintParts)
            If Not value Is Nothing AndAlso value.GetType Is GetType(Color) Then
                Dim col As Color
                If Not value = Color.Empty Then
                    col = value
                Else
                    col = Color.White
                End If

                graphics.FillRectangle(New SolidBrush(col), cellBounds)
                MyBase.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle)
            End If
            
        End Sub

        Protected Overrides Sub OnContentDoubleClick(ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
            Dim selector As New ColorDialog
            selector.AllowFullOpen = True
            selector.AnyColor = True
            If selector.ShowDialog = DialogResult.OK Then
                Me.Value = selector.Color
            End If
        End Sub

        Public Overrides ReadOnly Property DefaultNewRowValue() As Object
            Get
                Return Color.White
            End Get
        End Property

    End Class

End Namespace
